package com.xoa.service.budget;

import com.xoa.dao.email.EmailBodyMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.service.enclosure.impl.EnclosureServiceImpl;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/6/17.
 */
@Service
public class BudgetEnclosureService {

    @Resource
    AttachmentMapper attachmentMapper;

    @Autowired
    EmailBodyMapper emailBodyMapper;

    @Autowired
    private EnclosureServiceImpl enclosureService;

    public List<Attachment> budgetUpload(MultipartFile[] files, String company, String module, String flag) throws UnsupportedEncodingException {
        List<Attachment> list = this.budgetUploadReturn(files, company, module, flag);

        List<Attachment> attachmentList = new ArrayList<Attachment>();
        for (Attachment attachment : list) {
            attachment.setSize(attachment.getFileSize());

            // 存入attachment表
            enclosureService.saveAttachment(attachment);

            String attUrl = "AID=" + attachment.getAid().toString() +
                    "&MODULE=" + module + "&COMPANY=" + company +
                    "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" +
                    attachment.getAttachId().toString() + "&ATTACHMENT_NAME=" +
                    attachment.getAttachName() + "&FILESIZE=" + attachment.getFileSize();
            attachment.setAid(attachment.getAid());
            attachment.setAttUrl(attUrl);
            attachmentList.add(attachment);
        }
        return attachmentList;
    }

    public ToJson delete(@RequestParam("AID") String aid,
                         @RequestParam("MODULE") String module,
                         @RequestParam("YM") String ym,
                         @RequestParam("ATTACHMENT_ID") String attachmentId,
                         @RequestParam("ATTACHMENT_NAME") String attachmentName,
                         @RequestParam("COMPANY") String company,
                         HttpServletResponse response,
                         HttpServletRequest request) {
        ToJson tj = new ToJson();
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();

        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
        /*if(osName.toLowerCase().startsWith("win")){
            sb=sb.append(rb.getString("upload.win"));
		}else{
			sb=sb.append(rb.getString("upload.linux"));
		}*/
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        //String basePath="D:"+System.getProperty("file.separator");

        String path = null;
        if (StringUtils.checkNull(sb.toString())) {
            String a = request.getRealPath("");
            sb.append(a);
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
        append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).
                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
            path= sb.toString();
        } else if (attachmentName.contains("预算附件") || attachmentName.contains("合同") || attachmentName.contains("会议纪要")
                || attachmentName.contains("公共附件")) {
            sb.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).
                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
            path=sb.toString();
        } else {
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
        append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym).
                    append(System.getProperty("file.separator")).append(attachmentId).append(".").append(attachmentName);
            path=sb.toString();
        }




      /*  String path = sb.toString() + System.getProperty("file.separator") + company +
                System.getProperty("file.separator") + module + System.getProperty("file.separator") + ym + System.getProperty("file.separator") + attachmentId + "." + attachmentName;*/
        boolean flag = false;
        boolean flag1 = false;
        File file = new File(path);
        File newfile = new File(path + "." + Constant.delete);
        if (file.exists()) {// 路径为文件且不为空则进行删除

            //附件邮件模块限制
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("attachmentId", attachmentId);
            map.put("attachmentName", attachmentName);
            List<String> list = emailBodyMapper.getPrivAttachment(map);
            for (int i = 0, leg = list.size(); i < leg; i++) {
                String fromId = list.get(i);
                if (fromId.equals(userId)) {
                    flag1 = true;
                }
            }
            if (list == null || list.size() == 0 || flag1 == true) {
                Attachment attachment = new Attachment();
                attachment.setAid(Integer.parseInt(aid));
                attachment.setAttachId(attachmentId);
                attachment.setAttachName(attachmentName);
                attachmentMapper.delete(attachment);
                //file.delete();// 文件删除
                file.renameTo(newfile);
                flag = true;
            }

            //attachmentMapper.deleteByPrimaryKey(Integer.parseInt(aid));

        }
        if (flag == true) {
            tj.setFlag(0);
            tj.setMsg("OK");
        } else {
            tj.setFlag(1);
            tj.setMsg("false");
        }
        return tj;


    }

    public List<Attachment> upload2(MultipartFile[] files, String company, String module, String flag) throws UnsupportedEncodingException {
        List<Attachment> list = this.uploadReturn2(files, company, module, flag);
        List<Attachment> attachmentList = new ArrayList<Attachment>();
        for (Attachment attachment : list) {
            attachment.setSize(attachment.getFileSize());
            enclosureService.saveAttachment(attachment);
            String attUrl = "AID=" + attachment.getAid().toString() + "&MODULE=" + module + "&COMPANY=" + company + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId().toString() +
                    "&ATTACHMENT_NAME=" + attachment.getAttachName() + "&FILESIZE=" + attachment.getFileSize();
            attachment.setAid(attachment.getAid());
            attachment.setAttUrl(attUrl);
            attachmentList.add(attachment);
        }
        return attachmentList;
    }

    /**
     * 多文件上传（预算申请流程专用）
     *
     * @param files
     * @param company
     * @param module
     * @param flag    1-添加“合同-”前缀 2-添加“会议纪要”前缀
     * @return List<Attachment>
     */
    public List<Attachment> budgetUploadReturn(MultipartFile[] files, String company, String module, String flag) {
        // TODO 修改路径以配合预算管理的附件压缩
        if (files.length == 0) {
            return null;
        }
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String os = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        /*if(os.toLowerCase().startsWith("win")){
            sb=sb.append(rb.getString("upload.win"));
		}else{
			sb=sb.append(rb.getString("upload.linux"));
		}*/
        if (os.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        List<Attachment> list = new ArrayList<Attachment>();
        //当前年月
        String ym = new SimpleDateFormat("yyMM").format(new Date());
        //存储路径
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (StringUtils.checkNull(sb.toString())) {
            String a = request.getRealPath("");
            sb.append(a);
            sb.append(System.getProperty("file.separator")).
                    //append(System.getProperty("file.separator")).
                            append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym);
        } else {
            sb.append(System.getProperty("file.separator")).
                    //append(System.getProperty("file.separator")).
                            append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym);
        }
        String path = sb.toString();
        Attachment attachment = new Attachment();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            Long filesize = file.getSize();
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = file.getOriginalFilename().trim();

                //String fileName = new String(file.getOriginalFilename().getBytes("gbk"),"utf-8");
                String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));
                StringBuffer s = new StringBuffer();
                if (os.toLowerCase().startsWith("win")) {
                    s = s.append(fileName);
                } else {
                    try {
                        s = s.append(new String(fileName.getBytes(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                // 根据前端指令给上传文件添加前缀
                String prifix = "";
                if (flag.equals("1")) {
                    prifix = "合同-";
                } else if (flag.equals("2")) {
                    prifix = "会议纪要-";
                }

                fileName = prifix + fileName;
                //String newFileName = String.valueOf(attachID) + "." + fileName;
                String newFileName = String.valueOf(attachID) + "." + fileName;
                //String newFileName=new String(sf.getBytes(),"UTF-8");
                if (!file.isEmpty()) {
                    try {
                        if (!new File(path, newFileName).exists()) {
                            new File(path, newFileName).mkdirs();
                        }
                        // 转存文件
                        file.transferTo(new File(path, newFileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                File f = new File(path + newFileName);
                f.renameTo(new File(newFileName));
                byte isImg = 3;
                //获取后缀名
                String type = fileName.substring(fileName.indexOf(".") + 1);
                String[] imagType = {"jpg", "png", "bmp", "gif", "JPG", "PNG", "BMP", "GIF"};
                List<String> imageTyepLists = Arrays.asList(imagType);
                if (imageTyepLists.contains(type)) {
                    isImg = 0;
                } else {
                    isImg = 1;
                }
                byte a = 0;
                byte b = 2;
                //获得模块名
                int moduleID = 0;
                for (ModuleEnum em : ModuleEnum.values()) {
                    if (em.getName().equals(module.trim())) {
                        moduleID = em.getIndex();
                    }
                }

                byte mid = (byte) moduleID;
                attachment = new Attachment();
                attachment.setAttachId(attachID);
                attachment.setModule(mid);
                attachment.setAttachFile(fileName);
                //attachment.setAttachFile(newFileName);
                attachment.setAttachName(fileName);
                //attachment.setAttachName(newFileName);
                attachment.setYm(ym);
                attachment.setAttachSign(new Long(0));
                attachment.setDelFlag(a);
                attachment.setPosition(b);
                attachment.setIsImage(isImg);
                //String url = path + System.getProperty("file.separator") + newFileName;
                //attachment.setUrl(url);
                attachment.setFileSize(Convert.convertFileSize(filesize));
                attachment.setSize(Convert.convertFileSize(filesize));
                attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                list.add(attachment);
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    //多文件上传
    public List<Attachment> uploadReturn2(MultipartFile[] files, String company, String module, String flag) {
        if (files.length == 0) {
            return null;
        }
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String os = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        /*if(os.toLowerCase().startsWith("win")){
			sb=sb.append(rb.getString("upload.win"));
		}else{
			sb=sb.append(rb.getString("upload.linux"));
		}*/
        if (os.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        List<Attachment> list = new ArrayList<Attachment>();
        //当前年月
        String ym = new SimpleDateFormat("yyMM").format(new Date());
        //存储路径
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (StringUtils.checkNull(sb.toString())) {
            String a = request.getRealPath("");
            sb.append(a);
            sb.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym);
        } else {
            sb.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(module).append(System.getProperty("file.separator")).append(ym);
        }
        String path = sb.toString();
        Attachment attachment = new Attachment();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            Long filesize = file.getSize();
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = switchFileName(file.getOriginalFilename().trim(), flag);

                //String fileName = new String(file.getOriginalFilename().getBytes("gbk"),"utf-8");
                String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));
                StringBuffer s = new StringBuffer();
                if (os.toLowerCase().startsWith("win")) {
                    s = s.append(fileName);
                } else {
                    try {
                        s = s.append(new String(fileName.getBytes(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                //String newFileName = Integer.toString(attachID) + "." + fileName.toString();

                String newFileName = attachID + "." + fileName.toString();
                //String newFileName=new String(sf.getBytes(),"UTF-8");
                if (!file.isEmpty()) {
                    try {
                        if (!new File(path, newFileName).exists()) {
                            new File(path, newFileName).mkdirs();
                        }
                        // 转存文件
                        file.transferTo(new File(path, newFileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                File f = new File(path + newFileName);
                f.renameTo(new File(newFileName));
                byte isImg = 3;
                //获取后缀名
                String type = fileName.substring(fileName.indexOf(".") + 1);
                String[] imagType = {"jpg", "png", "bmp", "gif", "JPG", "PNG", "BMP", "GIF"};
                List<String> imageTyepLists = Arrays.asList(imagType);
                if (imageTyepLists.contains(type)) {
                    isImg = 0;
                } else {
                    isImg = 1;
                }
                byte a = 0;
                byte b = 2;
                //获得模块名
                int moduleID = 0;
                for (ModuleEnum em : ModuleEnum.values()) {
                    if (em.getName().equals(module.trim())) {
                        moduleID = em.getIndex();
                    }
                }

                byte mid = (byte) moduleID;
                attachment = new Attachment();
                attachment.setAttachId(attachID);
                attachment.setModule(mid);
                attachment.setAttachFile(fileName);
                attachment.setAttachName(fileName);
                attachment.setYm(ym);
                attachment.setAttachSign(new Long(0));
                attachment.setDelFlag(a);
                attachment.setPosition(b);
                attachment.setIsImage(isImg);
                //String url = path + System.getProperty("file.separator") + newFileName;
                //attachment.setUrl(url);
                attachment.setFileSize(Convert.convertFileSize(filesize));
                attachment.setSize(Convert.convertFileSize(filesize));
                attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                list.add(attachment);
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    private String switchFileName(String fileName, String flag) {
        if (flag == null || flag == "") return fileName;
        String newFileName = "";
        switch (flag) {
            case "0":
                newFileName = "公共附件-" + fileName;
                break;
            case "1":
                newFileName = "合同-" + fileName;
                break;
            case "2":
                newFileName = "会议纪要-" + fileName;
                break;
            default:
                newFileName = fileName;
                break;
        }
        return newFileName;
    }

}
